<?php
class LoginController extends Zend_Controller_Action{
	private $_auth;
	public function init(){
		$this->_auth = Zend_Auth::getInstance();
	}
	public function indexAction(){
		$loginForm = new Application_Form_Login();
		$loginForm->setAction($this->view->url(array('controller' => 'login','action' => 'login'),'default',true));
		$this->view->form = $loginForm;
	}
	public function loginAction(){
		$request = $this->getRequest();
		
		if($request->isPost()){
			$form = new Application_Form_Login();
			$data = $request->getPost();

			if($form->isValid($data)){
				$values = $form->getValues();
				$authAdapter = new Zend_Auth_Adapter_DbTable(Zend_Db_Table_Abstract::getDefaultAdapter(), 'web_admin', 'pseudo', 'password');
				$authAdapter->setIdentity($values['login']);
				$authAdapter->setCredential(md5($values['password']));
				if($this->_auth->authenticate($authAdapter)->isValid()){
					$this->storeAndRedirect($authAdapter);
				}else{
					$authAdapter->setTableName('web_users');
					if($this->_auth->authenticate($authAdapter)->isValid()){
						$this->storeAndRedirect($authAdapter);
					}else{
						$this->_helper->redirector('deny','error');
					}				
				}
			}else{
				$this->view->form = $form;
			}
		} else {
			$this->_helper->redirector('index','login');
		}	
	}
	private function storeAndRedirect(Zend_Auth_Adapter_DbTable $adap){
		$this->_auth->getStorage()->write($res = $adap->getResultRowObject(null,'password'));
		Zend_Session::regenerateId();
		$this->_helper->redirector('index','news');
	}
	public function logoutAction(){
		Zend_Auth::getInstance()->clearIdentity();
		Zend_Session::destroy();
		$this->_helper->redirector('index','news');
	}
}